package com.efuture.netrequestdemo.network

import android.content.Context
import com.efuture.netrequestdemo.app.MyApplication
import com.efuture.netrequestdemo.ui.BaseActivity
import com.efuture.netrequestdemo.utils.*
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.Response

/**

 *@description:Retrofit 接口参数定义
 * @author: zhaoshanshan
 * @date: 2022/3/24 5:51 下午

 */
object NetService {

    val apiService by lazy { ApiFactory.instance.create(AppGlobal.baseUrl,ApiService::class.java) }


    /**
     * 执行网络请求（结合kotlin 协程使用）
     * @param deferred 请求的接口
     * @param isValidateCode 是否验证code，如：登录是否过期
     * @param context 为null时，登录过期不跳登录页
     */
    suspend fun <T> request(deferred: Deferred<Response<T>>): T?  {
        LoadingUtils.showLoadIngDialog(AppUtils.getCurrentActivity()!!)
        return withContext(Dispatchers.IO){
            try {
                val response = deferred.await()
                if(null==response){
                    null
                }
                if (null!=response&&response.code()==200) {// 成功
                    response.body()
                } else {
                   null
                }
            } catch (e: Exception) {
                // 这里统一处理错误
                withContext(Dispatchers.Main){
                    ExceptionUtil.catchException(e)
                }
                null
            }
            finally {
                withContext(Dispatchers.Main){
                    LoadingUtils.disMissLoadIngDialog()
                }

            }
        }

    }
}